<?php


namespace api\modules\app\services;


use api\components\Common;
use api\modules\app\models\MetaArea;
use api\modules\app\models\Qrcode;
use api\modules\app\models\Section;
use Yii;
use yii\helpers\ArrayHelper;

class SectionService
{

    public static function search($params)
    {
        $conditions = self::getCondition($params);
        $query = Section::find()->andFilterWhere($conditions);
        $count = $query->count();
        Common::constructPage($query,$params);
        Common::constructSort($query,$params);
        $data = $query->asArray()->all();
        return [
            'count' => $count,
            'data' => $data,
        ];
    }

    private static function transferData($data)
    {
        $metas = MetaArea::find()->select(['name','code'])->andFilterWhere(['category' => ['区','街道'],'status' => 1])->asArray()->all();
        $metaMaps = ArrayHelper::map($metas,'code','name');
        if(!empty($data)){
            foreach ($data as &$row){
                $row['district_name'] = $metaMaps[$row['district_code']];
                $row['street_name'] = $metaMaps[$row['street_code']];
            }
        }
        return $data;
    }

    private static function getCondition($params)
    {
        $condition = [];
        if (isset($params['district_code'])) {
            $condition['district_code'] = $params['district_code'];
        }
        if (isset($params['street_code'])) {
            $condition['street_code'] = $params['street_code'];
        }
        return $condition;
    }

    public static function view($unitCode)
    {
        $unit = self::getSection($unitCode);
        $data = $unit->toArray();
        $district = MetaArea::findOne(['code' => $data['district_code']]);
        $street = MetaArea::findOne(['code' => $data['street_code']]);
        $data['district_name'] = $district->name;
        $data['street_name'] = $street->name;
        return $data;
    }

    private static function getSection($code)
    {
        $section = Section::findOne(['code' => $code]);
        if($section){
            return $section;
        }else{
            throw new \Exception('此路段不存在。');
        }
    }
}